package com.belf.console.service.impl;

import belf.migrate.training.LLMQueryTool;
import com.alibaba.fastjson2.JSONObject;
import com.belf.common.core.domain.AjaxResult;
import com.belf.common.utils.DateUtils;
import com.belf.console.domain.*;
import com.belf.console.mapper.GenerateDataInfoMapper;
import com.belf.console.service.*;
import com.belf.console.type.GenerateDataStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.belf.common.core.domain.AjaxResult.DATA_TAG;

@Service
public class GenerateDataInfoServiceImpl implements IGenerateDataInfoService {

    @Autowired
    private GenerateDataInfoMapper generateDataInfoMapper;

    @Autowired
    private IDataSourceInfoService dataSourceInfoService;

    @Autowired
    private IDataSqlTaskService dataSqlTaskService;

    @Autowired
    private IGenerateDataSqlService generateDataSqlService;

    @Autowired
    private IDataTaskConfService dataTaskConfService;

    @Override
    public int insertGenerateDataInfo(GenerateDataInfo dataInfo) {
        return generateDataInfoMapper.insertGenerateDataInfo(dataInfo);
    }

    @Override
    public List<GenerateDataInfo> selectGenerateDataInfoList(GenerateDataInfo generateDataInfo) {
        return generateDataInfoMapper.selectGenerateDataInfoList(generateDataInfo);
    }

    @Override
    public long selectDataCount(GenerateDataInfo generateDataInfo) {
        return generateDataInfoMapper.selectDataCount(generateDataInfo);
    }

    @Override
    public GenerateDataInfo selectGenerateDataInfoById(int id) {
        return generateDataInfoMapper.selectGenerateDataInfoById(id);
    }

    @Override
    public int updateGenerateDataInfo(GenerateDataInfo generateDataInfo) {
        return generateDataInfoMapper.updateGenerateDataInfo(generateDataInfo);
    }

    @Override
    public int deleteGenerateDataInfoById(String id) {
        return generateDataInfoMapper.deleteGenerateDataInfoById(id);
    }

    @Override
    public int deleteGenerateDataInfoByIds(String[] ids) {
        return generateDataInfoMapper.deleteGenerateDataInfoByIds(ids);
    }

    @Override
    public AjaxResult generateSourceData(GenerateDataInfo dataInfo) {
        try {
            dataInfo = generateDataInfoMapper.selectGenerateDataInfoById(dataInfo.getId());
            dataInfo.setStatus(GenerateDataStatus.RUNNING.getCode());
            generateDataInfoMapper.updateGenerateDataInfo(dataInfo);
            DataSourceInfo source = dataSourceInfoService.selectDataSourceInfoById(dataInfo.getSourceId());
            List<String> sqls = LLMQueryTool.query(dataInfo.getLLMModel(), dataInfo.getPrompt());

            int status = GenerateDataStatus.SUCCESS.getCode();
            List<GenerateDataSql> sqlList = new ArrayList<>();
            int index = 0;
            for (String sql : sqls) {
                if (sql.toUpperCase(Locale.ROOT).contains("CREATE SCHEMA") || sql.toUpperCase(Locale.ROOT).contains("GRANT")) {
                    continue;
                }
                DataSqlTask dataSqlTask = new DataSqlTask();
                dataSqlTask.setDatasourceId(source.getId());
                dataSqlTask.setSqlContext(sql);
                AjaxResult ajaxResult = dataSqlTaskService.executeSql(dataSqlTask);
                GenerateDataSql generateDataSql = new GenerateDataSql();
                generateDataSql.setSqlContent(sql);
                generateDataSql.setStatus(GenerateDataStatus.SUCCESS.getCode());
                generateDataSql.setMessage("执行成功");
                if (ajaxResult.isSuccess()) {
                    JSONObject jsonObject = JSONObject.parseObject(ajaxResult.get(DATA_TAG).toString());
                    if (jsonObject.getInteger("code") != 200) {
                        status = GenerateDataStatus.FAIL.getCode();
                        generateDataSql.setMessage(jsonObject.getString("msg"));
                        generateDataSql.setStatus(GenerateDataStatus.FAIL.getCode());
                    }
                }
                index++;
                generateDataSql.setSort(index);
                sqlList.add(generateDataSql);
            }
            dataInfo.setStatus(status);
            generateDataInfoMapper.updateGenerateDataInfo(dataInfo);
            int dataInfoId = dataInfo.getId();
            List<GenerateDataSql> temp = new ArrayList<>();
            for (GenerateDataSql generateDataSql : sqlList) {
                generateDataSql.setDataInfoId(dataInfoId);
                temp.add(generateDataSql);
                generateDataSqlService.batchInsertSql(temp, false);
            }
            generateDataSqlService.batchInsertSql(temp, true);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult createSyncTask(GenerateDataInfo dataInfo) {
        dataInfo = generateDataInfoMapper.selectGenerateDataInfoById(dataInfo.getId());
        DataSourceInfo soourceDataSourceInfo = dataSourceInfoService.selectDataSourceInfoById(dataInfo.getSourceId());
        DataSourceInfo sinkDataSourceInfo = dataSourceInfoService.selectDataSourceInfoById(dataInfo.getSinkId());
        DataTaskConf dataTaskConf = new DataTaskConf();
        String taskName = String.format("AI训练生成数据-%s-%s", DateUtils.dateTimeNow(), dataInfo.getId());
        dataTaskConf.setTaskName(taskName);
        String taskType = String.format("%s-%s", soourceDataSourceInfo.getType(), sinkDataSourceInfo.getType());
        dataTaskConf.setTaskType(taskType);
        dataTaskConf.setReaderBatch(1000L);
        /** 同步策略 1=只创建不执行,2=创建后执行 */
        dataTaskConf.setStrategy(2L);
        dataTaskConf.setTaskPolicy("ERROR_CONTINUE");
        dataTaskConf.setJobMode("ONCE");
        dataTaskConf.setJobType("SYNC_STRUCTURE");

        /**
         *  数据源配置，根据添加的数据源ID 和 数据库名称，
         */
        dataTaskConf.setSourceId(dataInfo.getSourceId());
        dataTaskConf.setSourceName(soourceDataSourceInfo.getDataSourceName());
        dataTaskConf.setSourceDatabase(soourceDataSourceInfo.getDatabaseName());
        dataTaskConf.setSourceDataSchema(soourceDataSourceInfo.getSchemaName());

        dataTaskConf.setSinkId(sinkDataSourceInfo.getId());
        dataTaskConf.setSinkName(sinkDataSourceInfo.getDataSourceName());
        dataTaskConf.setSinkDataSchema(sinkDataSourceInfo.getDatabaseName());
        dataTaskConf.setSinkDataSchema(sinkDataSourceInfo.getSchemaName());

        /**
         *  高级参数配置，没有配置不影响业务流程
         */
        dataTaskConf.setMonitorStatus(0);
        dataTaskConf.setSyncStatus(0);
        dataTaskConf.setBatchStatus(0);
        dataTaskConf.setTypeStatus(0);
        dataTaskConf.setTaskTypeScope("CREATE_TABLE,CREATE_VIEW,CREATE_FUNCTION,CREATE_TRIGGER,CREATE_PROCEDURE");

        /**  调度器 状态配置  "0=正常,1=暂停")  */
        dataTaskConf.setMonitorStatus(1);
        return AjaxResult.success(dataTaskConfService.insertDataTaskConf(dataTaskConf));
    }
}
